# Memento proxy for NLB's Web Archive Singapore 
import sys, os, re
import urllib
from baseHandler import *

__author__="aalsum"
__date__ ="$Aug 28, 2013 2:35:11 PM$"


baseuri = "http://was.nl.sg/wayback/*/"

class SingaporeHandler(BaseProxyHandler):

    def fetch_changes(self, req, requri, dt=None):
        # implement the changes list for this particular proxy

        uri = baseuri + requri
        try:
            fh = urllib.urlopen(uri)
        except:
            return self.error("Couldn't retrieve data from %s" % uri, req, status=404)
        data = fh.read()
        fh.close()
        regex = r'<a onclick="SetAnchorDate\(\'.*\'\);" href="http://was.nl.sg:80/wayback/[\S]*">';
        uriRegex = re.compile( regex )

        changes = []
        uris = re.findall(uriRegex, data)
        for u in uris:
            dtstr = u[27:41]
            loc = u[52:-2]
            dtstr += " GMT"
            dtobj = dateparser.parse(dtstr)
            changes.append((dtobj, loc, {'last': dtobj, 'obs' : 1}))

        return changes


def handler(req):
    hdlr = SingaporeHandler('sg')
    return basehandler(req, hdlr)


